package com.ruoyi.web.controller.product.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.entity.VO.product.ProductCategorySearchVO;
import com.ruoyi.common.entity.VO.product.ProductCategoryVO;
import com.ruoyi.common.entity.VO.shop.ShopSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopVO;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.product.service.IBackProductCategoryService;
import com.ruoyi.web.controller.shop.service.IBackShopService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/back/productCategory")
public class BackProductCategoryController extends BaseController {

    private String prefix = "product/category";

    @Resource
    private IBackProductCategoryService categoryService;

    @Resource
    private IBackShopService shopService;

    /**
     * 页面-商品分类列表
     *
     * @return
     */
    @RequiresPermissions("back:productCategory:list")
    @GetMapping()
    public String list() {
        return prefix + "/list";
    }

    /**
     * 页面-新增商品分类
     *
     * @return
     */
    @RequiresPermissions("back:productCategory:add")
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) {
        if (parentId == 0) {
            ProductCategoryVO categoryVO = new ProductCategoryVO();
            categoryVO.setId((long) 0);
            categoryVO.setCategoryName("无");
            mmap.put("category", categoryVO);
        } else {
            mmap.put("category", categoryService.getCategoryInfoById(parentId));
        }
        return prefix + "/add";
    }

    /**
     * 页面-编辑商品分类
     *
     * @param categoryId 商品分类ID
     * @return
     */
    @RequiresPermissions("back:productCategory:edit")
    @GetMapping("/edit/{categoryId}")
    public String edit(@PathVariable("categoryId") Long categoryId, ModelMap mmap) {
        ProductCategoryVO categoryVO = categoryService.getCategoryInfoById(categoryId);
        if (categoryVO != null && categoryVO.getParentId() == 0) {
            categoryVO.setParentName("无");
        }
        mmap.put("category", categoryVO);
        return prefix + "/edit";
    }

    /**
     * 页面-编辑店铺商品分类
     *
     * @return
     */
    @RequiresPermissions("back:productCategory:shopEdit")
    @GetMapping("/shopEdit/{shopId}")
    public String shopEdit(@PathVariable("shopId") Long shopId,ModelMap mmap) {
        ShopSearchVO shopSearchVO = new ShopSearchVO();
        shopSearchVO.setIsDelete(0);
        shopSearchVO.setReviewStatus(1);
        if(shopId==0L){
            List<ShopVO> shopList = shopService.searchList(shopSearchVO);
            mmap.put("shopList",shopList);
            mmap.put("shopId",1L);
            mmap.put("isShopSelect", true);
        }else{
            mmap.put("shopInfo",shopService.getShopInfoById(shopId));
            mmap.put("isShopSelect", false);
        }
        return prefix + "/shopEdit";
    }

    /**
     * 页面-选择分类树
     */
    @GetMapping("/selectCategoryTree/{categoryId}")
    public String selectCategoryTree(@PathVariable("categoryId") Long categoryId, ModelMap mmap) {
        if (categoryId == 0) {
            ProductCategoryVO categoryVO = new ProductCategoryVO();
            categoryVO.setId((long) 0);
            categoryVO.setCategoryName("无");
            mmap.put("category", categoryVO);
        } else {
            mmap.put("category", categoryService.getCategoryInfoById(categoryId));
        }
        return prefix + "/tree";
    }

    /**
     * 页面-选择分类树
     */
    @GetMapping("/selectTree/{categoryIdStr}")
    public String selectTree(@PathVariable("categoryIdStr") String categoryIdStr, ModelMap mmap) {
        if (categoryIdStr.equals("0")) {
            categoryIdStr = "";
        }
        mmap.put("categoryIdStr", categoryIdStr);
        mmap.put("isSelect", 1);
        return prefix + "/selectTree";
    }

    /**
     * 数据查询-商品分类列表（搜索）
     *
     * @param productCategorySearchVO
     * @return
     */
    @RequiresPermissions("back:productCategory:list")
    @PostMapping("/searchList")
    @ResponseBody
    public List<ProductCategoryVO> searchList(ProductCategorySearchVO productCategorySearchVO) {
        productCategorySearchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.CREDIT.getValue());
        List<ProductCategoryVO> list = categoryService.searchCategoryList(productCategorySearchVO);
        return list;
    }

    /**
     * 数据查询-校验商品分类名称
     */
    @PostMapping("/checkCategoryNameUnique")
    @ResponseBody
    public String checkCategoryNameUnique(ProductCategorySearchVO productCategorySearchVO) {
        return categoryService.checkCategoryNameUnique(productCategorySearchVO);
    }

    /**
     * 数据查询-加载分类列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        ProductCategorySearchVO productCategorySearchVO = new ProductCategorySearchVO();
        if (StringUtils.isNotEmpty(ServletUtils.getParameter("productId"))) {
            productCategorySearchVO.setProductId(Long.parseLong(ServletUtils.getParameter("productId")));
        }
        if (StringUtils.isNotEmpty(ServletUtils.getParameter("categoryIdStr"))) {
            if (!ServletUtils.getParameter("categoryIdStr").equals("0")) {
                productCategorySearchVO.setCategoryIdStr(ServletUtils.getParameter("categoryIdStr"));
            }
        }
        if (StringUtils.isNotEmpty(ServletUtils.getParameter("systemModule"))) {
            productCategorySearchVO.setSystemModule(Integer.valueOf(ServletUtils.getParameter("systemModule")));
        }
        if (StringUtils.isNotEmpty(ServletUtils.getParameter("isSelect"))) {
            productCategorySearchVO.setIsSelect(1);
        }
        List<Ztree> ztrees = categoryService.searchCategoryTree(productCategorySearchVO);
        return ztrees;
    }


    /**
     * 数据新增-添加商品分类
     *
     * @param categoryVO
     * @return
     */
    @Log(title = "总后台-商品分类管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("back:productCategory:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(ProductCategoryVO categoryVO) {
        ProductCategorySearchVO productCategorySearchVO = new ProductCategorySearchVO();
        if (Constants.FAIL.equals(categoryService.checkCategoryNameUnique(productCategorySearchVO))) {
            return error("新增分类失败'" + categoryVO.getCategoryName() + "'失败，分类名称已存在");
        }
        categoryVO.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        return toAjax(categoryService.insertCategory(categoryVO));
    }

    /**
     * 数据更新-编辑商品分类信息
     *
     * @param categoryVO
     * @return
     */
    @Log(title = "总后台-商品分类管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("back:productCategory:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(ProductCategoryVO categoryVO) {
        ProductCategorySearchVO categorySearchVO = new ProductCategorySearchVO();
        categorySearchVO.setCategoryId(categoryVO.getId());
        categorySearchVO.setCategoryName(categoryVO.getCategoryName());
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(categoryService.checkCategoryNameUnique(categorySearchVO))) {
            return error("修改分类'" + categoryVO.getCategoryName() + "'失败，分类名称已存在");
        } else if (categoryVO.getParentId().equals(categoryVO.getId())) {
            return error("修改分类'" + categoryVO.getCategoryName() + "'失败，上级分类不能是自身");
        }
        categoryVO.setUpdateBy(ShiroUtils.getSysUser().getLoginName());
        return AjaxResult.success(categoryService.updateCategory(categoryVO));
    }

    /**
     * 数据更新-删除商品分类
     *
     * @param categoryId 分类ID
     * @return
     */
    @Log(title = "总后台-商品分类管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("back:productCategory:remove")
    @GetMapping("/remove/{categoryId}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("categoryId") Long categoryId) {
        ProductCategorySearchVO categorySearchVO = new ProductCategorySearchVO();
        categorySearchVO.setParentId(categoryId);
        if (categoryService.countCategory(categorySearchVO) > 0) {
            return AjaxResult.error("存在下级分类,请先删除下级分类");
        }
        if (categoryService.checkCategoryExistProduct(categoryId)) {
            return AjaxResult.error("该商品分类存在关联商品,不允许删除");
        }
        return toAjax(categoryService.deleteCategoryById(categoryId));
    }
}
